package com.zhuqi.service.impl;

import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.excel.EasyExcel;
import com.zhuqi.configuration.FilePathList;
import com.zhuqi.configuration.PropertiesConfiguration;
import com.zhuqi.domain.UriExcel;
import com.zhuqi.service.AbstractCalcInterfaceCount;
import com.zhuqi.util.UrlReadListener;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.core.io.ResourceLoader;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;

import java.io.File;
import java.util.HashMap;
import java.util.List;
import java.util.Set;
import java.util.concurrent.CountDownLatch;

/**
 * @author : ZhuQi
 * @version : 时间:2022/8/9 14:18 版本:
 */
@Component
@Data
@Slf4j
public class CalcInterfaceCountImpl extends AbstractCalcInterfaceCount {

    @Autowired
    private FilePathList filePathList;

    @Autowired
    private PropertiesConfiguration configuration;

    @Autowired
    private ConfigurableApplicationContext context;

    @Autowired
    private ResourceLoader resourceLoader;

    /**
     * 必须根据配置初始化 map
     */
    @Override
    public void initMapAndKeyWords() {
        File file = new File(configuration.getExcelPath());
        if (!file.exists()) {
            log.warn("Uri 文件不存在，关闭容器!");
            context.close();
        }
        int size = filePathList.getList().size();
        map = new HashMap<>(size << 1, 0.75f);
        EasyExcel.read(file, UriExcel.class, new UrlReadListener(map)).sheet().doRead();
        keywords = configuration.getKeyword();
        log.info("文件读取完毕，URImap 大小:{}", map.size());
    }

    /**
     * 开始读取文件
     */
    @Override
    @Async("taskExecutor")
    public void doRead(String path, CountDownLatch countDownLatch) {
        String ThreadName = Thread.currentThread().getName();
        log.info(ThreadName + ":开始执行文件读取:{}", path);
        File file = new File(path);
        if (!file.isFile()) {
            log.warn("该地址不是文件 path:{}", path);
        }
        List<String> strings = FileUtil.readUtf8Lines(file);
        strings.stream().forEach(this::calcInterFaceCount);
        log.info(ThreadName + ":任务完成");
        countDownLatch.countDown();
    }


    /**
     * 计算接口 次数
     *
     * @param str 每行数据
     */
    @Override
    public void calcInterFaceCount(String str) {
        Set<String> keySets = map.keySet();
        for (String key : keySets) {
            if (StrUtil.isNotBlank(keywords)) {
                if (str.contains(key) && str.contains(keywords)) {
                    map.get(key).increment();
                    continue;
                }
            }
            if (str.contains(key)) {
                map.get(key).increment();
            }
        }
    }
}
